// 导入 React 核心功能
import { useState, useEffect } from 'react'
// 导入 React Router 的导航钩子，用于页面跳转
import { useNavigate } from 'react-router-dom'
// 导入 Ant Design Mobile 组件库
import { ResultPage, Card, SearchBar, Swiper, Grid, Tabs, Button, Toast, SpinLoading } from 'antd-mobile'
// 导入 Ant Design Mobile 图标
import { DownOutline, RightOutline, StarOutline } from 'antd-mobile-icons'
// 导入 Redux hooks
import { useSelector } from 'react-redux'
import type { RootState } from '../../store/types'
// 导入权限检查函数
import { hasPermission } from '../../utils/permission'

// 导入样式文件
import './index.css'
// 导入自定义请求工具
import request from '../../api/request'
// 导入健康资讯列表组件
import HealthInformationList from '../../components/HealthInformationList'
// 导入病友圈相关类型和API函数
import { type SickCircleItem, addSickCircleCollection, cancelSickCircleCollection } from '../../api/sickCircle'

/**
 * 数据类型定义
 * 定义了首页所需的各种数据结构
 */

/**
 * 轮播图数据项接口
 */
interface BannerItem {
  id: number          // 轮播图唯一标识符
  imageUrl: string    // 轮播图片URL
  title?: string      // 轮播图标题（可选）
  link?: string       // 轮播图链接（可选）
}

/**
 * 科室数据项接口
 */
interface DepartmentItem {
  id: number              // 科室唯一标识符
  pic: string             // 科室图标URL
  departmentName: string  // 科室名称
  rank?: number           // 科室排名（可选）
}

/**
 * 疾病数据项接口
 */
interface DiseaseItem {
  id: number          // 疾病唯一标识符
  departmentId: number // 所属科室ID
  name: string        // 疾病名称
}

/**
 * 药品分类接口
 */
interface MedicineCategory {
  id: number      // 分类唯一标识符
  name: string    // 分类名称
  rank: number    // 分类排名
}

/**
 * 药品数据项接口
 */
interface MedicineItem {
  id: number              // 药品唯一标识符
  drugsCategoryId: number // 所属分类ID
  name: string           // 药品名称
  picture: string        // 药品图片URL
}

/**
 * 医生数据项接口
 */
interface DoctorItem {
  doctorId: number           // 医生唯一标识符
  doctorName: string         // 医生姓名
  imagePic: string          // 医生头像URL
  jobTitle: string          // 医生职称
  inauguralHospital: string // 就职医院
  praise: number            // 好评率百分比
  serverNum: number         // 服务次数
  servicePrice: number      // 服务价格
  praiseNum: number         // 好评数量
  badNum: number           // 差评数量
}

/**
 * 首页组件
 * 包含轮播图、科室导航、医生推荐、药品分类、病友圈等功能模块
 * 这是应用的主页面，集成了所有核心功能入口
 */
function Index() {
  // 获取路由导航函数，用于页面跳转
  const navigate = useNavigate()

  // ==================== 状态管理 ====================
  
  // 获取当前用户邮箱
  const userEmail = useSelector((state: RootState) => state.info.email)
  
  /**
   * 科室列表数据
   * 用于展示首页的科室导航网格
   */
  const [list, setList] = useState<DepartmentItem[]>([])
  
  /**
   * 轮播图数据
   * 用于首页顶部的轮播展示
   */
  const [bannerData, setBannerData] = useState<BannerItem[]>([])
  
  /**
   * 专家问诊科室列表
   * 用于专家问诊选项卡的数据源
   */
  const [departmentList, setDepartmentList] = useState<DepartmentItem[]>([])
  
  /**
   * 病症数据缓存
   * 按科室ID分组存储病症数据，避免重复请求
   */
  const [diseaseData, setDiseaseData] = useState<{ [key: number]: DiseaseItem[] }>({})
  
  /**
   * 当前选中的科室Tab索引
   * 用于控制专家问诊选项卡的激活状态
   */
  const [activeTab, setActiveTab] = useState(0)
  
  /**
   * 药品分类数据
   * 用于药品分类选项卡的数据源
   */
  const [medicineCategories, setMedicineCategories] = useState<MedicineCategory[]>([])
  
  /**
   * 当前选中的药品分类Tab索引
   * 用于控制药品分类选项卡的激活状态
   */
  const [activeMedicineTab, setActiveMedicineTab] = useState(0)
  
  /**
   * 药品数据缓存
   * 按分类ID分组存储药品数据，避免重复请求
   */
  const [medicineData, setMedicineData] = useState<{ [key: number]: MedicineItem[] }>({})
  
  /**
   * 医生数据缓存
   * 按科室ID分组存储医生数据，避免重复请求
   */
  const [doctorsByDept, setDoctorsByDept] = useState<{ [key: number]: DoctorItem[] }>({})
  
  /**
   * 病友圈列表数据
   * 用于展示病友圈动态
   */
  const [sickCircleList, setSickCircleList] = useState<SickCircleItem[]>([])
  
  /**
   * 病友圈加载状态
   * 用于显示加载指示器
   */
  const [sickCircleLoading, setSickCircleLoading] = useState(false)
  
  /**
   * 收藏加载状态
   * 按病友圈ID存储收藏操作的加载状态，防止重复操作
   */
  const [collectionLoading, setCollectionLoading] = useState<{ [key: number]: boolean }>({})

  // ==================== API 数据获取函数 ====================
  
  /**
   * 获取科室列表数据
   * 用于首页科室导航网格的展示
   */
  const getDepartmentList = () => {
    request.get('/health/share/knowledgeBase/v1/findDepartment').then((res) => {
      if (res.status === 200) {
        setList(res.data.result)
      }
    })
  }

  /**
   * 获取轮播图数据
   * 用于首页顶部的轮播展示
   */
  const getBannerData = () => {
    request.get('/health/share/v1/bannersShow').then((res) => {
      if (res.status === 200) {
        const bannerData = res.data.result || []
        setBannerData(bannerData)
      } else {
        setBannerData([])
      }
    }).catch((error) => {
      console.error('获取轮播图数据失败:', error)
      setBannerData([])
    })
  }

  /**
   * 获取专家问诊科室数据
   * 用于专家问诊选项卡的数据源，并自动获取第一个科室的相关数据
   */
  const getExpertDepartmentList = () => {
    request.get('/health/share/knowledgeBase/v1/findDepartment').then((res) => {
      if (res.status === 200) {
        setDepartmentList(res.data.result)
        // 获取第一个科室的病症和医生数据
        if (res.data.result && res.data.result.length > 0) {
          getDiseaseData(res.data.result[0].id)
          getDoctorList(res.data.result[0].id)
        }
      }
    })
  }

  /**
   * 获取药品分类数据（模拟数据）
   * 由于后端暂无药品分类接口，使用模拟数据
   */
  const getMedicineCategories = () => {
    const mockData = [
      { id: 1, name: '感冒用药', rank: 1 },
      { id: 3, name: '风湿骨伤', rank: 2 },
      { id: 4, name: '两性健康', rank: 3 },
      { id: 2, name: '儿童用药', rank: 4 },
      { id: 5, name: '三高用药', rank: 5 },
      { id: 6, name: '其它药品', rank: 6 }
    ]
    setMedicineCategories(mockData)
    // 获取第一个分类的药品数据
    if (mockData.length > 0) {
      getMedicineData(mockData[0].id)
    }
  }

  /**
   * 获取病症数据
   * 根据科室ID获取对应的病症列表
   * 
   * @param departmentId 科室ID
   */
  const getDiseaseData = (departmentId: number) => {
    request.get(`/health/share/knowledgeBase/v1/findDiseaseCategory?departmentId=${departmentId}`).then((res) => {
      if (res.status === 200) {
        // 使用函数式更新，将新数据合并到现有缓存中
        setDiseaseData(prev => ({
          ...prev,
          [departmentId]: res.data.result || []
        }))
      }
    }).catch((error) => {
      console.error('获取病症数据失败:', error)
    })
  }

  /**
   * 获取医生列表
   * 根据科室ID获取对应的医生列表
   * 
   * @param deptId 科室ID
   * @param page 页码，默认为1
   * @param count 每页数量，默认为6
   * @param condition 排序条件，默认为1
   */
  const getDoctorList = (deptId: number, page: number = 1, count: number = 6, condition: number = 1) => {
    request.get('/health/user/inquiry/v1/findDoctorList', {
      params: { deptId, condition, page, count }
    }).then((res) => {
      if (res.status === 200) {
        // 确保返回的数据是数组格式
        const result = Array.isArray(res.data.result) ? res.data.result : []
        // 使用函数式更新，将新数据合并到现有缓存中
        setDoctorsByDept((prev) => ({ ...prev, [deptId]: result }))
      }
    }).catch((error) => {
      console.error('获取医生列表失败:', error)
    })
  }

  /**
   * 获取药品数据
   * 根据药品分类ID获取对应的药品列表
   * 
   * @param drugsCategoryId 药品分类ID
   */
  const getMedicineData = (drugsCategoryId: number) => {
    request.get(`/health/share/knowledgeBase/v1/findDrugsKnowledgeList?drugsCategoryId=${drugsCategoryId}&page=1&count=5`).then((res) => {
      if (res.status === 200) {
        // 为药品数据添加固定图片（模拟数据）
        const medicineImages = [
          'https://images.unsplash.com/photo-1584308666744-24d5c474f2ae?w=200&h=200&fit=crop',
          'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=200&h=200&fit=crop',
          'https://images.unsplash.com/photo-1587854692152-cbe660dbde88?w=200&h=200&fit=crop',
          'https://images.unsplash.com/photo-1576091160399-112ba8d25d1f?w=200&h=200&fit=crop',
          'https://images.unsplash.com/photo-1584308666744-24d5c474f2ae?w=200&h=200&fit=crop'
        ]

        // 为每个药品分配一个图片
        const medicineList = (res.data.result || []).map((medicine: MedicineItem, index: number) => ({
          ...medicine,
          picture: medicineImages[index % medicineImages.length]
        }))

        // 使用函数式更新，将新数据合并到现有缓存中
        setMedicineData(prev => ({
          ...prev,
          [drugsCategoryId]: medicineList
        }))
      }
    }).catch((error) => {
      console.error('获取药品数据失败:', error)
    })
  }

  /**
   * 获取病友圈数据
   * 获取首页展示的病友圈动态列表
   */
  const getSickCircleData = () => {
    setSickCircleLoading(true)
    request.get('/health/user/sickCircle/v1/findSickCircleList', {
      params: {
        departmentId: 1,
        page: 1,
        count: 3
      }
    }).then((res) => {
      if (res.status === 200) {
        if (res.data.result && Array.isArray(res.data.result)) {
          // 为数据添加collectionFlag字段，确保收藏状态正确
          const processedList = res.data.result.map((item: Record<string, unknown>) => ({
            ...item,
            collectionFlag: item.collectionFlag || 0
          })) as SickCircleItem[]
          setSickCircleList(processedList)
        } else {
          setSickCircleList([])
        }
      } else {
        setSickCircleList([])
      }
    }).catch((error) => {
      console.error('获取病友圈数据失败:', error)
      setSickCircleList([])
    }).finally(() => {
      setSickCircleLoading(false)
    })
  }

  // ==================== 工具函数 ====================
  
  /**
   * 格式化时间戳为相对时间
   * 将毫秒时间戳转换为"X天前"、"X小时前"、"X分钟前"等易读格式
   * 
   * @param timestamp 时间戳
   * @returns 格式化后的时间字符串
   */
  const formatTime = (timestamp: number) => {
    const now = new Date().getTime()
    const diff = now - timestamp
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
    const hours = Math.floor(diff / (1000 * 60 * 60))
    const minutes = Math.floor(diff / (1000 * 60))

    if (days > 0) return `${days}天前`
    if (hours > 0) return `${hours}小时前`
    if (minutes > 0) return `${minutes}分钟前`
    return '刚刚'
  }

  /**
   * 获取悬赏文本
   * 根据悬赏金额返回对应的显示文本
   * 
   * @param amount 悬赏金额
   * @returns 悬赏文本
   */
  const getBountyText = (amount: number) => {
    return amount > 0 ? `悬赏${amount}H币` : '无悬赏'
  }

  // ==================== 事件处理函数 ====================
  
  /**
   * 处理收藏功能
   * 根据当前收藏状态执行添加或取消收藏操作
   * 
   * @param item 病友圈项目
   * @param e 点击事件对象
   */
  const handleCollection = async (item: SickCircleItem, e: React.MouseEvent) => {
    e.stopPropagation() // 阻止事件冒泡，避免触发跳转
    
    // 防止重复操作
    if (collectionLoading[item.sickCircleId]) return
    
    // 设置当前项目的加载状态
    setCollectionLoading(prev => ({ ...prev, [item.sickCircleId]: true }))
    
    try {
      const isCollected = item.collectionFlag === 1
      
      if (isCollected) {
        // 取消收藏
        const response = await cancelSickCircleCollection({ sickCircleId: item.sickCircleId })
        if (response.status === '0000') {
          // 更新本地状态
          setSickCircleList(prev => prev.map(listItem => 
            listItem.sickCircleId === item.sickCircleId 
              ? { 
                  ...listItem, 
                  collectionFlag: 0,
                  collectionNum: Math.max(0, (listItem.collectionNum || 0) - 1)
                }
              : listItem
          ))
          Toast.show({
            content: '取消收藏成功',
            position: 'center',
          })
        } else {
          Toast.show({
            content: response.message || '取消收藏失败',
            position: 'center',
          })
        }
      } else {
        // 添加收藏
        const response = await addSickCircleCollection({ sickCircleId: item.sickCircleId })
        if (response.status === '0000') {
          // 更新本地状态
          setSickCircleList(prev => prev.map(listItem => 
            listItem.sickCircleId === item.sickCircleId 
              ? { 
                  ...listItem, 
                  collectionFlag: 1,
                  collectionNum: (listItem.collectionNum || 0) + 1
                }
              : listItem
          ))
          Toast.show({
            content: '收藏成功',
            position: 'center',
          })
        } else {
          Toast.show({
            content: response.message || '收藏失败',
            position: 'center',
          })
        }
      }
    } catch (error) {
      console.error('收藏操作失败:', error)
      Toast.show({
        content: '网络错误，请稍后重试',
        position: 'center',
      })
    } finally {
      // 清除加载状态
      setCollectionLoading(prev => ({ ...prev, [item.sickCircleId]: false }))
    }
  }

  /**
   * 跳转到评论页面
   * 如果传入了病友圈ID则跳转到对应评论页，否则跳转到第一个病友圈的评论页
   * 
   * @param sickCircleId 病友圈ID（可选）
   */
  const goCommentPage = (sickCircleId?: number) => {
    const targetId = sickCircleId ?? sickCircleList[0]?.sickCircleId
    navigate(`/pinglun${targetId ? `?id=${targetId}` : ''}`)
  }

  /**
   * 处理科室选项卡切换
   * 切换科室时自动加载对应的病症和医生数据
   * 
   * @param key 选项卡的key值
   */
  const handleTabChange = (key: string) => {
    const index = parseInt(key)
    setActiveTab(index)
    if (departmentList[index]) {
      const departmentId = departmentList[index].id
      // 如果该科室的病症数据未加载，则加载
      if (!diseaseData[departmentId]) {
        getDiseaseData(departmentId)
      }
      // 如果该科室的医生数据未加载，则加载
      if (!doctorsByDept[departmentId]) {
        getDoctorList(departmentId)
      }
    }
  }

  /**
   * 处理药品分类选项卡切换
   * 切换药品分类时自动加载对应的药品数据
   * 
   * @param key 选项卡的key值
   */
  const handleMedicineTabChange = (key: string) => {
    const index = parseInt(key)
    setActiveMedicineTab(index)
    if (medicineCategories[index]) {
      const drugsCategoryId = medicineCategories[index].id
      // 如果该分类的药品数据未加载，则加载
      if (!medicineData[drugsCategoryId]) {
        getMedicineData(drugsCategoryId)
      }
    }
  }

  // ==================== 组件生命周期 ====================
  
  /**
   * 组件初始化
   * 组件挂载时获取所有必要的数据
   */
  useEffect(() => {
    getDepartmentList()        // 获取科室列表
    getBannerData()           // 获取轮播图数据
    getExpertDepartmentList() // 获取专家问诊科室数据
    getMedicineCategories()   // 获取药品分类数据
    getSickCircleData()       // 获取病友圈数据
  }, [])

  // ==================== 组件渲染 ====================
  
  return (
    <div>
      {/* 页面头部 */}
      <ResultPage
        status='success'
        title={
          <div className='header-bar'>
            <div className='header-title'>
              <span className='brand'>妙手医生</span>
              <span className='dot'>·</span>
              <span className='hospital'>妙手互联网医院</span>
            </div>
            <div className='location'>
              杭州 <DownOutline />
            </div>
          </div>
        }
        description={
          <div className='searchbar searchbar-compact'>
            <div onClick={() => navigate('/search')} style={{ cursor: 'pointer' }}>
              <SearchBar
                placeholder='搜索医生、医院、药品、疾病症状'
                onFocus={() => navigate('/search')}
              />
            </div>
          </div>
        }
      >
        {/* 功能入口卡片 */}
        <ResultPage.Card className='section-card'>
          <Grid columns={3} gap={8}>
            <Grid.Item>
              <div className='action-item'>
                <div className='action-icon action-blue'>👨‍⚕️</div>
                <h3 className='action-title'>预约挂号</h3>
                <p className='action-desc'><span className='highlight'>30W+</span>专家入驻</p>
              </div>
            </Grid.Item>
            <Grid.Item>
              <div className='action-item'>
                <div className='action-icon action-orange'>💬</div>
                <h3 className='action-title'>极速问诊</h3>
                <p className='action-desc'>1分钟内接诊</p>
              </div>
            </Grid.Item>
            <Grid.Item>
              <div className='action-item'>
                <div className='action-icon action-green'>🏥</div>
                <h3 className='action-title'>线上购药</h3>
                <p className='action-desc'>全国送药上门</p>
              </div>
            </Grid.Item>
          </Grid>
        </ResultPage.Card>

        {/* 科室导航 */}
        <Card style={{ marginTop: 6, padding: '8px' }}>
          <Grid columns={4} gap={8}>
            {list.map((item) => (
              <Grid.Item key={item.id}>
                <div className='dept-item' onClick={()=>navigate('/fen')}>
                  <div className='dept-thumb'>
                    <img src={item.pic} alt={item.departmentName} />
                  </div>
                  <span className='dept-name'>{item.departmentName}</span>
                </div>
              </Grid.Item>
            ))}
          </Grid>
        </Card>

        {/* 轮播图 */}
        <div style={{ marginTop: '10px', height: '100px' }}>
          <Swiper
            autoplay={true}
            autoplayInterval={3000}
            loop={true}
            defaultIndex={0}
            style={{ '--height': '100px' }}
          >
            {bannerData.map((image, index) => (
              <Swiper.Item key={index}>
                <div style={{
                  width: '100%',
                  height: '100px',
                  backgroundImage: `url(${image.imageUrl})`,
                  backgroundSize: 'cover',
                  backgroundPosition: 'center',
                  backgroundRepeat: 'no-repeat'
                }} />
              </Swiper.Item>
            ))}
          </Swiper>
        </div>

        {/* 专家问诊选项卡 */}
        <Card style={{ marginTop: '10px', padding: '12px' }}>
          <div className='expert-section'>
            <div className='expert-header'>
              <span className='expert-title'>我要问专家</span>
              <RightOutline className='expert-arrow' />
            </div>

            <Tabs
              className='department-tabs'
              defaultActiveKey='0'
              activeKey={activeTab.toString()}
              onChange={handleTabChange}
              style={{
                '--title-font-size': '14px',
                '--content-padding': '0',
              }}
            >
              {departmentList.map((item, index) => (
                <Tabs.Tab title={item.departmentName} key={index}>
                  <div className='tab-content'>
                    {/* 医生列表预览 */}
                    <div className='disease-list'>
                      <h4 className='disease-title'>推荐医生</h4>
                      {!doctorsByDept[item.id] && (
                        <div className='disease-grid'>加载中...</div>
                      )}
                      {doctorsByDept[item.id] && (
                        <div className='doctor-list'>
                          {doctorsByDept[item.id].slice(0, 4).map((doctor) => (
                            <div 
                              key={doctor.doctorId} 
                              className='doctor-card'
                              onClick={() => navigate(`/doctor-detail/${doctor.doctorId}`)}
                              style={{ cursor: 'pointer' }}
                            >
                              <div className='doctor-avatar'>
                                <img
                                  src={doctor.imagePic}
                                  alt={doctor.doctorName}
                                  onError={(e) => {
                                    (e.target as HTMLImageElement).src = 'http://10.59.9.18/images/health/doctor/default.jpg'
                                  }}
                                />
                              </div>
                              <div className='doctor-info'>
                                <div className='doctor-row'>
                                  <div className='doctor-name'>{doctor.doctorName}</div>
                                  <div className='doctor-price'>¥{doctor.servicePrice}</div>
                                </div>
                                <div className='doctor-title-hospital'>
                                  {doctor.jobTitle} · {doctor.inauguralHospital}
                                </div>
                                <div className='doctor-stats'>好评率 {doctor.praise}% · 服务 {doctor.serverNum}</div>
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>

                    {/* 查看更多医生按钮 */}
                    <div className='more-diseases'>
                      <Button
                        className='more-diseases-btn'
                        color='primary'
                        fill='outline'
                        onClick={() => navigate('/doctor-list', { state: { departmentId: item.id } })}>
                        查看更多医生
                      </Button>
                    </div>
                  </div>
                </Tabs.Tab>
              ))}
            </Tabs>
          </div>
        </Card>

        {/* 药品分类选项卡 */}
        <Card style={{ marginTop: '10px', padding: '12px' }}>
          <div className='medicine-section'>
            <div className='medicine-header'>
              <span className='medicine-title'>我要买药</span>
              <span className='medicine-more'>更多 &gt;</span>
            </div>

            <Tabs
              className='medicine-tabs'
              defaultActiveKey='0'
              activeKey={activeMedicineTab.toString()}
              onChange={handleMedicineTabChange}
              style={{
                '--title-font-size': '14px',
                '--content-padding': '0',
              }}
            >
              {medicineCategories.map((category, index) => (
                <Tabs.Tab title={category.name} key={index}>
                  <div className='tab-content'>
                    {/* 药品列表 */}
                    {medicineData[category.id] && (
                      <div className='medicine-list'>
                        <h4 className='medicine-title'>常见药品</h4>
                        <div className='medicine-cards'>
                          {medicineData[category.id].map((medicine) => (
                            <div
                              key={medicine.id}
                              className='medicine-card'
                              onClick={() => navigate(`/drug-detail/${medicine.id}`)}
                              style={{ cursor: 'pointer' }}
                            >
                              <div className='medicine-card-content'>
                                <div className='medicine-card-image'>
                                  <img
                                    src={medicine.picture}
                                    alt={medicine.name}
                                    onError={(e) => {
                                      const target = e.target as HTMLImageElement
                                      target.style.display = 'none'
                                      target.nextElementSibling?.classList.remove('hidden')
                                    }}
                                  />
                                  <div className='medicine-placeholder hidden'>
                                    <span className='medicine-brand'>[品牌]</span>
                                  </div>
                                </div>
                                <div className='medicine-card-info'>
                                  <div className='medicine-card-name'>{medicine.name}</div>
                                  <div className='medicine-card-brand'>{medicine.name}</div>
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}

                    {/* 加载中状态 */}
                    {!medicineData[category.id] && (
                      <div className='medicine-loading'>
                        <p>加载中...</p>
                      </div>
                    )}
                  </div>
                </Tabs.Tab>
              ))}
            </Tabs>
          </div>
        </Card>

        {/* 健康讲堂视频 */}
        <Card style={{ marginTop: '10px', padding: '12px' }}>
          <div className='video-section'>
            <div className='video-header'>
              <span className='video-title'>健康讲堂</span>
              <span className='video-more' onClick={() => navigate('/app/cases')} style={{ cursor: 'pointer' }}>
                更多 &gt;
              </span>
            </div>
            <div className='video-preview'>
              <div className='video-placeholder' onClick={() => navigate('/app/cases')}>
                <div className='video-icon'>🎥</div>
                <p>观看健康视频</p>
                <span className='video-desc'>专业医生讲解健康知识</span>
              </div>
            </div>
          </div>
        </Card>

        {/* 病友圈列表 */}
        <Card style={{ marginTop: '10px', padding: '12px' }}>
          <div className='sick-circle-section'>
            <div className='sick-circle-header'>
              <span className='sick-circle-title'>病友圈</span>
              <span className='sick-circle-more' onClick={() => navigate('/sick-circle')} style={{ cursor: 'pointer' }}>
                更多 &gt;
              </span>
            </div>

            <div className='sick-circle-content'>
              {sickCircleLoading ? (
                <div className='sick-circle-loading'>
                  <p>加载中...</p>
                </div>
              ) : sickCircleList.length > 0 ? (
                <div className='sick-circle-list'>
                  {sickCircleList.map((item) => (
                    <div key={item.sickCircleId} className='sick-circle-item' onClick={() => navigate(`/sick-circle-detail/${item.sickCircleId}`)}>
                      <div className='sick-circle-item-header'>
                        <div className='sick-circle-avatar'>
                          <span>👤</span>
                        </div>
                        <div className='sick-circle-info'>
                          <h4 className='sick-circle-item-title'>{item.title}</h4>
                          <div className='sick-circle-meta'>
                            <span className='sick-circle-time'>{formatTime(item.releaseTime)}</span>
                            <span className='sick-circle-bounty' style={{
                              backgroundColor: item.amount > 0 ? '#fff7e6' : '#f5f5f5',
                              color: item.amount > 0 ? '#fa8c16' : '#999'
                            }}>
                              {getBountyText(item.amount)}
                            </span>
                          </div>
                        </div>
                      </div>

                      <p className='sick-circle-detail'>{item.detail}</p>

                      <div className='sick-circle-stats'>
                        <span 
                          className={`stat-item ${collectionLoading[item.sickCircleId] ? 'loading' : ''}`}
                          onClick={(e) => handleCollection(item, e)}
                        >
                          {collectionLoading[item.sickCircleId] ? (
                            <SpinLoading color="primary" style={{ fontSize: '12px' }} />
                          ) : (
                            <StarOutline className={item.collectionFlag === 1 ? 'active' : ''} />
                          )}
                          {item.collectionNum}
                        </span>
                        <span className='stat-item'>
                          <span className='stat-icon'>💬</span>
                          {item.commentNum}
                        </span>
                      </div>
                      <div style={{ textAlign: 'right', marginTop: 6 }}>
                        <Button size='mini' fill='outline' onClick={(e) => { e.stopPropagation(); goCommentPage(item.sickCircleId) }}>评论</Button>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className='sick-circle-empty'>
                  <p>暂无病友圈动态</p>
                </div>
              )}

              <div className='sick-circle-actions'>
                <Button 
                  color='primary' 
                  fill='outline' 
                  size='small' 
                  style={{ marginRight: '8px' }}
                  onClick={() => navigate('/sick-circle')}
                >
                  查看更多
                </Button>
                <Button color='primary' size='small' onClick={() => {
                  // 检查权限，如果没有权限则提示
                  if (!userEmail) {
                    Toast.show('请先登录')
                    return
                  }
                  if (!hasPermission(userEmail, 'publish')) {
                    Toast.show('暂无权限，无法发布内容')
                    return
                  }
                  navigate('/sick-circle-publish')
                }}>
                  发表动态
                </Button>
              </div>
            </div>
          </div>
        </Card>

        {/* 健康资讯列表 */}
        <HealthInformationList />
      </ResultPage>
      <div className='test'>1111</div>
    </div>
  )
}

export default Index
